package com.easy.service.impl;

import com.easy.bean.Staff;
import com.easy.mapper.StaffDao;
import com.easy.service.LoginService;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import com.easy.util.passwordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    StaffDao staffDao;

    public Staff logininfo(String token) {
        //token中存的用户的id
        Object id = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        if(id==null){
            return null;
        }
        Staff staff = staffDao.one(Integer.parseInt(id.toString()));
        return staff;
    }

    @Override
    public Staff updatePassword(String token, String oldPassword, String newPassword) {
        // 通过token获取用户信息
        Object id = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        if(id==null){
            throw new RuntimeException("未登录");
        }

        Staff staff = staffDao.one(Integer.parseInt(id.toString()));
        if(staff == null){
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码
        String encryptionPassword = staff.getPassword();
        if(!passwordUtil.checkPassword(oldPassword, encryptionPassword)){
            throw new RuntimeException("旧密码错误");
        }

        // 更新密码
        staff.setPassword(passwordUtil.getEncryption(newPassword));
        staffDao.edit(staff);

        // 返回更新后的用户信息
        return staffDao.one(staff.getId());
    }


    @Override
    public String login(Staff staff) {
        //登录逻辑
        //1，通过用户名查询用户
        Staff result=staffDao.getByPhone(staff.getPhone());
        if(result==null){
            throw new RuntimeException("登录异常");
        }
        //2,验证密码
        String password=staff.getPassword();
        String encryptionPassword=result.getPassword();
        if(!passwordUtil.checkPassword(password,encryptionPassword)){
            throw new RuntimeException("密码错误");
        }

        //3,返回结果token
        String token= TokenUtil.getToken(result.getId(),"staff");
        return token;
    }
}
